package com.ghck.server.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component("userCache")
public class AjkUserCache implements UserCache {
	
	Logger logger = LoggerFactory.getLogger(AjkUserCache.class); 
    
	@Autowired
    private RedisTemplate<String, Object> template;
    
    @Override
    public UserDetails getUserFromCache(String accessId) {
    	UserDetails user = null;
    	try{
    		user = (UserDetails)template.opsForValue().get(accessId);
    	}catch(Exception ex){
    		logger.error("redis error",ex);
    	}
    	
        return user;
    }

    @Override
    public void putUserInCache(UserDetails user) {
        String accessId = user.getUsername();
        
        removeUserFromCache(accessId);
        template.opsForValue().set(accessId, user);
    }

    @Override
    public void removeUserFromCache(String accessId) {
    	template.opsForValue().getOperations().delete(accessId);
    }
    
}